import cgi
import os
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp import util
import jinja2
import simplejson as json
from main import DEBUG, Handler, template_env, memcache_get, cache_control
import models


class ProjectEditHandler(Handler):

    """Edit project details."""

    possibilities = {'true': True, 'false': False, 'null': None}

    def get(self, project_name):
        """Present a form to edit the Python 3 status of a project."""
        entity = models.Project.get_by_key_name(project_name)
        if entity is None:
            self.error(404)
        else:
            template = template_env.get_template('project_edit.html')
            self.response.out.write(template.render(project=entity))

    def post(self, project_name):
        """Update the Python 3 status of a project."""
        status = self.request.get('status')
        # XXX evil POST data (or missing status)
        assert status in self.possibilities
        support = self.possibilities[status]
        note = cgi.escape(self.request.get('note'))
        # XXX no note
        successful = db.run_in_transaction(self.txn, project_name, support, note)
        if not successful:
            self.error(404)
        else:
            self.redirect('/pypi/%s' % project_name)

    def txn(self, name, support, note):
        """Update the entity appropriately."""
        entity = models.Project.get_by_key_name(name)
        if entity is None:
            return False
        if support:
            entity.py3k_support_added(note)
        else:
            entity.py3k_support = support
            entity.py3k_note = note
            entity.py3k_added = None
        entity.put()
        return True


class ProjectDisplayHandler(Handler):

    """Display details about a project."""

    @cache_control
    @memcache_get
    def get(self, project_name):
        """Retrieve a project's details.

        If the specified cannot be found, see if the lowercase name exists. If
        it does, do a permanent redirect to the proper project name. Else
        return a 404.

        """
        entity = models.Project.get_by_key_name(project_name)
        if not entity:
            query = models.Project.all()
            query = query.filter('lowercase_name =', project_name.lower())
            entity = query.get()
            if not entity:
                self.response.out.write('Oh, sorry! No project named %s' %
                                        project_name)
                self.error(404)
            else:
                self.redirect('/pypi/%s' % entity.key().name(), permanent=True)
        else:
            template = template_env.get_template('project.html')
            self.response.out.write(template.render(project=entity))


urls = [('/pypi/(.+)', ProjectDisplayHandler),
        ('/edit/(.+)', ProjectEditHandler),
       ]

def application():
    return webapp.WSGIApplication(urls, debug=DEBUG)

def main():
    util.run_wsgi_app(application())


if __name__ == '__main__':
    main()
